package org.fast.project.app.config;

import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;

import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

/**
 * 验证器配置
 *
 * @author junG
 * @date 2022/11/27
 */
@Configuration
public class ValidatorConfiguration {

    /**
     * 方法验证后置处理程序
     * 路由层方法校验器 启用后在Action路由上添加@Validated
     * 以支持对@RequestParam @PathVariable型参数的校验
     *
     * @return {@link MethodValidationPostProcessor}
     */
    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor();
        /*设置validator模式为快速失败返回*/
        postProcessor.setValidator(validator());
        return postProcessor;
    }

    /**
     * 启用验证器
     * 设置Validator校验类
     * 启用快速失败 这样多重级联校验一层失败就全部返回
     *
     * @return {@link Validator}
     */
    @Bean
    public Validator validator(){
        try (ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
            .configure()
            .failFast(true)
            .buildValidatorFactory()) {
            return validatorFactory.getValidator();
        }
    }
}
